package org.chameleon.datasource.manager;



import org.chameleon.datasource.cache.CacheRefreshManager;
import org.chameleon.datasource.cache.DefaultCacheFreshStore;
import org.chameleon.lang.ConfigAbleManager;
import org.chameleon.lang.cache.Refreshable;

import java.util.Map;
import java.util.Objects;

/**
 * 抽象的配置管理
 * @see AbsConfigManager#callBack(Map<String ,T>)  对配置数据数据更新
 * @see AbsConfigManager#getConfig(T) 获取对应的配置
 * @param <T>
 */
public abstract class AbsConfigManager<T> implements ConfigAbleManager<T> {

    private final DefaultCacheFreshStore<T> defaultCacheFreshStore ;

    private final CacheRefreshManager<Map<String ,T>> cacheRefreshManager ;

    public AbsConfigManager() {
        cacheRefreshManager = new CacheRefreshManager<>();
        defaultCacheFreshStore = new DefaultCacheFreshStore<>();
        cacheRefreshManager.addRefreshListener( this);
    }


    @Override
    public T getConfig(T t) {
        final String key = buildCacheKey(t);
        T result = defaultCacheFreshStore.get(key);
        if (Objects.isNull(result)){
            result = loadFromDateSource(t);
            defaultCacheFreshStore.put(key,t);
        }
        return result;
    }

    @Override
    public void callBack(Map<String ,T> map) {
        cacheRefreshManager.fresh(map);
    }

    @Override
    public void refresh(Map<String,T> map) {
        defaultCacheFreshStore.refresh(map);
    }

    @Override
    public void addRefreshListener(Refreshable<Map<String, T>> refreshable) {
        cacheRefreshManager.addRefreshListener(refreshable);
    }
}
